﻿using BaseUtils;
using BaseUtils.AppConfig;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using UserManage;
using Button = BaseUtils.AppConfig.Button;
using Page = BaseUtils.AppConfig.Page;

namespace 拧紧抢反转程序.froms
{
    public partial class AuthorityManage : Form
    {

        private UserIndex UI;
        private UserInfo UserInfo;

        private Panel panel; // 容器控件

        // 定义 Label 控件的大小和间距
        int LabelWidth = 100;
        int LabelHeight = 20;
        static int gap = 10;

        // 初始化位置变量
        int x = 10;
        int y = gap;

        int PanelY = 50;

        public AuthorityManage(UserIndex parent, UserInfo _userInfo)
        {
            UI = parent;
            UserInfo = _userInfo;
            InitializeComponent();

            // 创建 Panel 控件
            panel = new Panel();
            panel.AutoScroll = true; // 启用滚动条
            panel.Dock = DockStyle.Fill; // 填充整个窗体

            // 将 Panel 添加到窗体
            this.Controls.Add(panel);

            RenderRoleComponent();

            GetVisitPages().ForEach(page =>
            {
                SetPanel(page);
                x = 10; y = gap;
            });

            ShowUserInfo();
        }

        /// <summary>
        /// 获取可访问的按钮
        /// </summary>
        /// <returns></returns>
        public List<Page> GetVisitPages()
        {
            List<Visit> UserVisits = Authentication.CurrentLoginUser?.Visits;
            
            if (Authentication.CurrentLoginUser.Level == 5)
            {
                return BaseService.AppConfig.Securitys.Pages;
            }
            List<Page> VisitPages = new List<Page>();

            BaseService.AppConfig.Securitys.Pages.ForEach(vi =>
            {
                foreach (Visit user in UserVisits)
                {
                    if (user.Key == vi.Name)
                    {
                        Page page = new Page();
                        page.Name = vi.Name;
                        page.Desc = vi.Desc;

                        List<Button> buttons = new List<Button>();
                        vi.Buttons.ForEach(b =>
                        {
                            if (user.Names.Contains(Authentication.SingleControlName(page.Name, b.Name)))
                            {
                                buttons.Add(b);
                            }
                        });
                        page.Buttons = buttons;

                        VisitPages.Add(page);
                    }
                }
            });

            return VisitPages;
        }

        /// <summary>
        /// 加载角色下拉控件
        /// </summary>
        private void RenderRoleComponent()
        {
            BaseService.AppConfig.Securitys.Roles.ForEach(role =>
            {
                if (Authentication.CurrentLoginUser?.Level >= role.Level)
                {
                    comboBox1.Items.Add(role.Name);
                }
            });
        }

        /// <summary>
        /// 显示用户信息
        /// </summary>
        private void ShowUserInfo()
        {
            textBox1.Text = UserInfo.UserName;
            comboBox1.Text = UserInfo.LevelName;
        }

        public Panel SetPanel(Page Group)
        {
            // 创建 GroupBox 控件
            GroupBox groupBox = new GroupBox();
            groupBox.Text = Group.Desc; // 设置组的标题
            groupBox.Name = Group.Name; // 设置组的标题
            groupBox.Location = new Point(gap, PanelY); // 设置组的位置
            groupBox.Size = new Size(this.Width - 40, Group.Buttons.Count * (LabelHeight + gap) + 2 * gap); // 设置组的大小

            PanelY += groupBox.Height + 10;
            // 将 GroupBox 添加到 Panel 控件中
            panel.Controls.Add(groupBox);

            // 循环创建多个 Label 控件

            // 循环创建多个 Label 控件并添加到 GroupBox 控件中
            foreach (Button text in Group.Buttons)
            {

                groupBox.Controls.Add(SetLabel(Group, text));

                // 更新位置变量
                x += LabelWidth + gap;
                if (x + LabelWidth + gap > panel.ClientSize.Width) // 判断是否需要换行
                {
                    x = gap;
                    y += LabelHeight + gap;
                }
            }

            return panel;
        }

        public Label SetLabel(Page Group, Button Item)
        {
            // 创建 Label 对象
            Label label = new Label();
            // 设置 Label 的属性
            label.Text = Item.Desc;
            label.Name = Authentication.SingleControlName(Group.Name, Item.Name);
            label.Size = new Size(LabelWidth, LabelHeight);
            label.AutoSize = true; // 自适应内容大小
            label.Padding = new Padding(3);
            label.Cursor = Cursors.Hand;

            IsShowColor(Group, label);
            //label.ForeColor = Color.Blue;
            // label.BackColor = Color.Blue;
            // 添加绘制事件处理程序
            label.Paint += (sender, e) =>
            {
                // 获取 Label 的文本范围
                Rectangle textBounds = label.DisplayRectangle;
                textBounds.Height -= 1; // 减去1像素以确保下划线在文本下方

                // 绘制下划线
                using (Pen pen = new Pen(Color.Blue, 1))
                {
                    e.Graphics.DrawLine(pen, textBounds.Left, textBounds.Bottom, textBounds.Right, textBounds.Bottom);
                }
            };

            // 添加点击事件处理程序
            label.Click += (sender, e) =>
            {

                Label s = ((Label)sender);

                // 获取对应的文本

                string ParentName = s.Parent.Name;
                string labelText = s.Name.Replace(ParentName, "");
                int i = UserInfo.Visits.FindIndex(v => v.Key == ParentName);
                if (i < 0)
                {
                    Visit visit = new Visit();
                    visit.Key = ParentName;
                    visit.Names = new HashSet<string> { labelText };
                    UserInfo.Visits.Add(visit);

                    return;
                }
                foreach (Visit item in UserInfo.Visits)
                {
                    if (item.Key == ParentName)
                    {
                        string ex = item.Names.Where(x => x == labelText).FirstOrDefault();
                        if (string.IsNullOrEmpty(ex))
                        {
                            s.ForeColor = Color.Green;
                            item.Names.Add(labelText);
                        }
                        else
                        {
                            s.ForeColor = Color.Black;
                            item.Names.Remove(ex);
                        }
                    }
                }
            };

            label.Location = new Point(x + 10, y + 20);

            return label;
        }

        private void IsShowColor(Page Group, Label label)
        {
            if (UserInfo.Visits == null || UserInfo.Visits.Count <= 0)
            {
                return;
            }
            //if (UserInfo.Level==5)
            //{
            //    label.ForeColor = Color.Green;
            //    return;
            //}

            UserInfo.Visits.ForEach(x =>
            {
                if (x.Key == Group.Name)
                {
                    string name = x.Names.Where(n => n == label.Name).FirstOrDefault();
                    if (!string.IsNullOrEmpty(name))
                    {
                        label.ForeColor = Color.Green;
                    }
                }
            });
        }

        private void button1_Click(object sender, System.EventArgs e)
        {
        
            if (string.IsNullOrEmpty(comboBox1.Text))
            {
                MessageBox.Show("请选择角色");
                return;
            }
            Role role = BaseService.AppConfig.Securitys.Roles.Where(x => x.Name == comboBox1.Text).FirstOrDefault();
            if (role == null)
            {
                MessageBox.Show("角色错误，请重新选择");
                return;
            }
            UserInfo.UserName = textBox1.Text;
            UserInfo.LevelName = comboBox1.Text;
            UserInfo.Level = role.Level;

            UI.UpdateUser(UserInfo);
            Close();
        }

    }
}
